#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *

#ui.py main file
from ui import MainKontrolcu
from dialogs import *

#modules to make it work and to make it translatable
import os
import sys
import gettext
import hashlib
import platform

#Opening a web page in a web browser
from constants import URL
from constants import HELPURL

#For about box
from constants import NAME
from constants import LICENSE_NAME
from constants import DESCRIPTION
from constants import VERSION

#For using unicode utf-8
reload(sys).setdefaultencoding("utf-8")

if os.name == "posix":
    gettext.install("kontrolcu", unicode=1)
if os.name == "nt":
    try:
        lang=gettext.locale.getdefaultlocale()
        lang=lang[0]
        textlang = gettext.translation('kontrolcu', 'locale', languages=[lang])
        textlang.install(unicode=1)
    except:
        pass

ABOUT=""" <font color=black size=30><b>Kontrolcu %s</b></font></b><p>

<p>%s</p>

<p><b>%s:</b> %s</p>

<p><b>%s:</b> %s </p>

<p><b>%s:</b></p>

<p>Taha Doğan Güneş, tdgunes@gmail.com</p>
<p>Osman Karagöz, osmank3@gmail.com</p>

<p><b>%s:</b></p>
<p>de: Stefan Wilhelm, sw1976de [at] googlemail.com</p>
<p>es: Klemens Häckel, click3d [at] linuxmail.org</p>
<p>fr: Philippe Svetoslavsky, philsvet [at] gmail.com</p>
<p>it: Mirsda Hoxha, mir3ho [at] gmail.com</p>
<p>nl: Antoon Tolboom, atolboo [at] gmail.com</p>
<p>tr: Okan Okuroğulları, ookurugullari [at] gmail.com</p>
<p>sv: Patrik Karlsson, patrik [at] pardus.nu</p>

<p><b>Logo:</b></p>

<p>Cemalettin Kara, cemalettinkara [at] gmail.com</p>
<p>Creative Commons: BY-NC-SA</p>
"""% (VERSION, DESCRIPTION, _("Web Site"), URL, _("License"), LICENSE_NAME,  _("Developers"),  _("Translators"))


#To import kontrolcu's library \\ No need to write try: except: here
MODULEPATH = os.getcwd()[:-3] + "src"
sys.path.append(MODULEPATH)
from libkontrolcu import *

class MainQt(MainKontrolcu):
    def __init__(self, parent=None):
        super(MainQt, self).__init__(parent)

        #SIGNALS for MainKontrolcu - MainWindow
        self.connect(self.aboutthis, SIGNAL("clicked()"), self.aboutKontrolcu)
        self.connect(self.aboutqt, SIGNAL("clicked()"), self.aboutQt)
        self.connect(self.fontsizer, SIGNAL("valueChanged(int)"), self.resizeit)
        self.connect(self.helpme, SIGNAL("clicked()"), self.openMyWebPage)

        #SIGNALS for MainKontrolcu - tabconlayout
        self.connect(self.tabconlayout.saveToFile, SIGNAL("clicked()"), self.saveCheckToFile)
        self.connect(self.tabconlayout.addFile, SIGNAL("clicked()"), self.addFiles)
        self.connect(self.tabconlayout.checkit, SIGNAL("clicked()"), self.checkEvent)
        self.connect(self.tabconlayout.saveToClip, SIGNAL("clicked()"), self.sendTextToClip)
        self.connect(self.tabconlayout.deleteSelected, SIGNAL("clicked()"),  self.deleteSelectedItem)
        self.connect(self.tabconlayout.typecombox, SIGNAL("highlighted(int)"), self.cleanEvent)

        #SIGNALS for MainKontrolcu - tabfilelayout
        self.connect(self.tabfilelayout.selectedConBut, SIGNAL("clicked()"), self.openControlFile)
        self.connect(self.tabfilelayout.selectedDirBut, SIGNAL("clicked()"), self.openDirectory)
        self.connect(self.tabfilelayout.analyzeIt, SIGNAL("clicked()"), self.analyzeThem)

        #SIGNALS for MainKontrolcu - tabcomplayout
        self.connect(self.tabcomplayout.selectedSumBut, SIGNAL("clicked()"), self.pasteTheNumber)
        self.connect(self.tabcomplayout.selectedFileBut, SIGNAL("clicked()"), self.openNormalFile)
        self.connect(self.tabcomplayout.compareIt, SIGNAL("clicked()"), self.compareThem)
        self.connect(self.tabcomplayout.selectedSumLine, SIGNAL("editingFinished()"), self.checkTheNumber)

        #False them
        self.tabcomplayout.compareIt.setEnabled(False)
        self.checktypes = { "md5" : hashlib.md5,
                           "sha1" : hashlib.sha1,
                         "sha224" : hashlib.sha224,
                         "sha256" : hashlib.sha256,
                         "sha384" : hashlib.sha384,
                         "sha512" : hashlib.sha512 }
        self.checkcontrols = { 32 : hashlib.md5,
                               40 : hashlib.sha1,
                               56 : hashlib.sha224,
                               64 : hashlib.sha256,
                               96 : hashlib.sha384,
                               128 : hashlib.sha512 }
        #Save, clear is needs checkstatus.
        self.checkstatus = False
        #If checkstatus is False means there is no check now!
# MainKontrolcu Functions
    def openMyWebPage(self):
        QDesktopServices.openUrl(QUrl(HELPURL))
    def resizeit(self):
        myfont = QFont()
        myfont.setPointSize(self.fontsizer.value())
        self.tabconlayout.mainlist.setFont(myfont)
        self.tabcomplayout.combrowser.setFont(myfont)
        self.tabfilelayout.filebrowser.setFont(myfont)
    def aboutKontrolcu(self):
        QMessageBox.about(self, _("About Kontrolcu"), ABOUT) #Ok, now
    def aboutQt(self):
        QMessageBox.aboutQt(self, _("About Qt"))

# TabComplayout Functions
    def openNormalFile(self):
        selectedFile = QFileDialog.getOpenFileName(self, _("Kontrolcu - Add a  File"),".")
        self.tabcomplayout.selectedFileLine.setText(selectedFile)
        print _("Compare file: ") + selectedFile
    def pasteTheNumber(self):
        print makeYellow(_("Start Paste"))
        clipboard = QApplication.clipboard()
        self.tabcomplayout.selectedSumLine.setText(clipboard.text(clipboard.Clipboard))
        print _("Pasted:") + " " + self.tabcomplayout.selectedSumLine.text()
        self.checkTheNumber()
        print makeYellow(_("End of Paste"))
    def checkTheNumber(self):
        print makeYellow(_("Start Number Check"))
        controls = { 32 : "md5sum",
                     40 : "sha1sum",
                     56 : "sha224sum",
                     64 : "sha256sum",
                     96 : "sha384sum",
                    128 : "sha512sum"}
        self.result = controls.get(len(self.tabcomplayout.selectedSumLine.text()))
        if self.result:
            self.tabcomplayout.checksumlabel.setText(_("Your checksum: ") + self.result +_(" is OK!"))
            self.tabcomplayout.compareIt.setEnabled(True)
            self.tabcomplayout.combrowser.clear()
            print makeGreen(_("Number is OK!"))
        elif self.tabcomplayout.selectedSumLine.text() == "":
            print makeBlue(_("There is no number!"))
        elif self.result != "":
            self.tabcomplayout.checksumlabel.setText(_("Your checksum is invalid!"))
            self.tabcomplayout.compareIt.setEnabled(False)
            print makeRed(_("Number is NOT OK!"))
        print makeYellow(_("End of Number Check"))
    def compareThem(self):
        print makeYellow(_("Start Compare"))
        self.tabcomplayout.compareIt.setEnabled(False)
        if self.tabcomplayout.selectedFileLine.text():
            finalresultsize =  os.stat(self.tabcomplayout.selectedFileLine.text()).st_size
            cptype = self.checktypes.get(str(self.result[:3]))
            if finalresultsize >  (((1024)**2)*50):
                files = []
                files.append(self.tabcomplayout.selectedFileLine.text())
	        checkdialog = CheckDialog(worklist=files, 
                                          finalnumber=finalresultsize)
	        progressbar = checkdialog.progress
	        thatlabel = checkdialog.filename
	        cancelbutton = checkdialog.cancelbutton
	        pi = ProgressIncrement(progressbar, 
                                       checktype=cptype, 
                                       filelist=files, 
                                       label=thatlabel)
                                       #listwidget=self.tabconlayout.mainlist)
                checkdialog.progressunit = pi
                def closeDialog():
                    results = str(pi.resultlist[0]).split("  ")[0]
                    print _("Checksum:") + " " + self.tabcomplayout.selectedSumLine.text()
                    print _("File's Check") + " " + results
                    self.tabcomplayout.combrowser.append(_("Checksum:")+ " " + self.tabcomplayout.selectedSumLine.text())
                    self.tabcomplayout.combrowser.append(_("File's Check:")+ " " + results)
                    if results == self.tabcomplayout.selectedSumLine.text():
                        self.tabcomplayout.combrowser.append("<font color=green>" + _("Result: OK!") + "</font>")
                        print makeGreen(_("Result: OK!"))
                    else:
                        self.tabcomplayout.combrowser.append("<font color=red>" + _("Result: Wrong!") + "</font>")
                        print makeRed(_("Result: Wrong!"))
                    pi.quit()
                    checkdialog.close()

                def terminateIt():
                    self.tabcomplayout.combrowser.append( "<font color=red>" + _("Check is canceled by user!") + "</font>")
                    pi.terminate()
                    checkdialog.close()
                    #for i in results:
                       #self.tabconlayout.mainlist.addItem(i)
	        QObject.connect(pi, SIGNAL("incrementProgressBar()"), pi.incrementProgressBar)
                QObject.connect(pi, SIGNAL("operationFinished()"), closeDialog)
                QObject.connect(checkdialog.cancelbutton, SIGNAL("clicked(bool)"), terminateIt)
                pi.start()
	        checkdialog.exec_()

            else:
                FileObject = CUnit(path=self.tabcomplayout.selectedFileLine.text(), value=self.tabcomplayout.selectedSumLine.text())
                FileObject.Compare()
                self.tabcomplayout.combrowser.append(_("Checksum:") + FileObject.ValueReceived)
                self.tabcomplayout.combrowser.append(_("File's Check:") + FileObject.ValueReal)
                print _("Checksum:") + " " + FileObject.ValueReceived
                print _("File's Check") + " " + FileObject.ValueReal
                if FileObject.CompValue:
                    self.tabcomplayout.combrowser.append("<font color=green>" + _("Result: OK!") + "</font>")
                    print makeGreen(_("Result: OK!"))
                else:
                    self.tabcomplayout.combrowser.append("<font color=red>" + _("Result: Wrong!") + "</font>")
                    print makeRed(_("Result: Wrong!"))
            print makeYellow(_("End of Compare"))

#  Tabfilelayout Functions
    def openControlFile(self):
        selectedCon = QFileDialog.getOpenFileName(self, 
                                                  "Kontrolcu" + " - " + _("Add a Control File"),
                                                  ".",
                                                  _("Control Types") + "(*.md5sum *.sha1sum *.sha224sum *.sha256sum *.sha384sum *.sha512sum);;" + _("Plain Text File") + "(*)")
        self.tabfilelayout.selectedConLine.setText(selectedCon)
    def openDirectory(self):
        selectedDir = QFileDialog.getExistingDirectory(self, "Kontrolcu" + " - " + _("Add a Directory"),".")
        self.tabfilelayout.selectedDirLine.setText(selectedDir)

    def analyzeThem(self):
        self.tabfilelayout.filebrowser.clear()
        print _("- Start Analyze Process -")
        mymessagetemp = FromFile(str(self.tabfilelayout.selectedConLine.text()),str(self.tabfilelayout.selectedDirLine.text()))
        mymessage = {}
        #Turning keys and values
        for i in mymessagetemp.keys():
            if mymessagetemp[i] == "0":
                mymessage[i] = mymessagetemp[i]
            else:
                mymessage[mymessagetemp[i]] = i
        del mymessagetemp

        filelist=[]
        finalresultsize = 0
        for i in mymessage.keys():
            CType = self.checkcontrols.get(len(mymessage[i]))
            if mymessage[i] != "0":
                filelist.append(i)
        for i in filelist:
            finalresultsize += os.stat(i).st_size 
        if finalresultsize >  (((1024)**2)*50):
               files = filelist
	       checkdialog = CheckDialog(worklist=files, 
                                         finalnumber=finalresultsize)
	       progressbar = checkdialog.progress
	       thatlabel = checkdialog.filename
	       cancelbutton = checkdialog.cancelbutton
	       pi = ProgressIncrement(progressbar, 
                                      checktype=CType, 
                                      filelist=files, 
                                      label=thatlabel)
                                      #listwidget=self.tabconlayout.mainlist)
               def closeDialog():
                   dlist = pi.resultlist
                   for n in dlist:
                       summary, file2 = n.split("  ")
                       for i in filelist:
                           if file2 == i[-len(file2):]:
                               file2 = i
                       if mymessage[file2] == summary:
                           mymessage[file2] = "+"
                       else:
                           mymessage[file2] = "-"
                   pi.quit()
                   checkdialog.close()

               def terminateIt():
                   self.tabfilelayout.filebrowser.append("<font color=red>" +_("Check is canceled by user!") +"</font>") 
                   pi.terminate()
                   checkdialog.close()
                   #for i in results:
                       #self.tabconlayout.mainlist.addItem(i)
	       QObject.connect(pi, SIGNAL("incrementProgressBar()"), pi.incrementProgressBar)
               QObject.connect(pi, SIGNAL("operationFinished()"), closeDialog)
               QObject.connect(checkdialog.cancelbutton, SIGNAL("clicked(bool)"), terminateIt)

               pi.start()
	       checkdialog.exec_()
        else:
            for i in filelist:
                object = CUnit(path=i, value=mymessage[i])
                object.Compare()
                if object.CompValue == True:
                    mymessage[i] = "+"
                else:
                    mymessage[i] = "-"
        if mymessage is not None:
            print _("Check Result(s):")
            for i in mymessage.keys():
                if mymessage[i] == "+":
                    self.tabfilelayout.filebrowser.append("<font color=green>" + (_("%s is OK.") % os.path.split(i)[1]) + "</font>")
	            print makeGreen( _("%s is OK.") % os.path.split(i)[1])
                elif mymessage[i] == "-":
                    self.tabfilelayout.filebrowser.append("<font color=red>" + (_("%s is modified or changed.") % os.path.split(i)[1]) + "</font>")
                    print makeRed( _("%s is modified or changed.") % os.path.split(i)[1])
                elif mymessage[i] == "0":
                    self.tabfilelayout.filebrowser.append("<font color=blue>" + (_("%s is missing.") % os.path.split(i)[1]) + "</font>")
                    print makeYellow( _("%s is missing.") % os.path.split(i)[1])
                else:
                    self.tabfilelayout.filebrowser.append(os.path.split(i)[1])


#  Tabconlayout Functions 
    def saveCheckToFile(self):
        if self.checkstatus:
            print makeYellow( _("- Start Save Process -"))
            rnumber = 0
            savelist = []
            checktext = self.tabconlayout.typecombox.currentText() + "sum"
            variables = _("Control Type") + " (*."+ checktext + ");;" + _("Text File") + " (*.txt)"
            newfilepath = QFileDialog.getSaveFileName(self, "Kontrolcu" +  _("- Save the Check"), _("unnamed") + "." +checktext,variables)
            print _("Selected path to save the check:")
            print makeBlue(newfilepath)
            try:
                openfile = open(newfilepath, 'w')
                while True:
                    try:
                        savelist.append(self.tabconlayout.mainlist.item(rnumber).text())
                        rnumber +=1
                    except:
                        break
            
                for i in savelist:
                    openfile.write(i + "\n")
                openfile.close()
                print makeGreen(_("File is saved succesfully."))
                print makeYellow(_("- End of the process -"))
            except IOError, (error_no, error):
                if error_no is 13:
                    errortext= _("Error:(while saving) You don't have permission to save.")
                    self.showError(errortext)
                    print makeRed(errortext)
                else:
                    errortext= _("Error:(unknown) or user closed the save dialog.")
                    self.showError(errortext)
                    print makeRed(errortext)
                print makeYellow(_("- End of errors -"))

    def deleteSelectedItem(self):
        self.tabconlayout.mainlist.takeItem(self.tabconlayout.mainlist.currentRow())

    def sendTextToClip(self):
        clipboard = QApplication.clipboard()
        selecteditem = self.tabconlayout.mainlist.currentItem()
        if selecteditem:
            clipboard.setText(selecteditem.text())

    def cleanEvent(self): #To Clean List
        if self.checkstatus:
            self.tabconlayout.mainlist.clear()
            if os.name != "nt":
                self.tabconlayout.mainlist.cstatus = True #Because of a fatal error in windows
            self.checkstatus = False

    def checkEvent(self): 
        if self.checkstatus is not True:
            ctype = self.checktypes.get(str(self.tabconlayout.typecombox.currentText()))
            finalresultsize = self.tabconlayout.mainlist.getSize()
	    if finalresultsize >  (((1024)**2)*50): # 50 mb 
               files = self.tabconlayout.mainlist.getListItems()
	       checkdialog = CheckDialog(worklist=files, 
                                         finalnumber=finalresultsize)
	       progressbar = checkdialog.progress
	       thatlabel = checkdialog.filename
	       cancelbutton = checkdialog.cancelbutton
	       pi = ProgressIncrement(progressbar, 
                                      checktype=ctype, 
                                      filelist=files, 
                                      label=thatlabel)
                                      #listwidget=self.tabconlayout.mainlist)
	       
               def closeDialog():
                   self.checkstatus = True  # To say, check is done!        
                   self.tabconlayout.mainlist.cstatus = False # No drag and drop please!
                   self.tabconlayout.mainlist.clear()
                   try:
                       results = pi.resultlist
                       for i in results:
                           self.tabconlayout.mainlist.addItem(i)
                   except:
                       pass
                   pi.quit()
                   checkdialog.close()

               def terminateIt():
                   self.checkstatus = True
                   self.tabconlayout.mainlist.cstatus = False
                   self.tabconlayout.mainlist.clear()
                   self.tabconlayout.mainlist.addItem(_("Check is canceled by user!"))
                   pi.terminate()
                   checkdialog.close()
                   #for i in results:
                       #self.tabconlayout.mainlist.addItem(i)
	       QObject.connect(pi, SIGNAL("incrementProgressBar()"), pi.incrementProgressBar)
               QObject.connect(pi, SIGNAL("operationFinished()"), closeDialog)
               QObject.connect(checkdialog.cancelbutton, SIGNAL("clicked(bool)"), terminateIt)

               pi.start()
	       checkdialog.exec_()
                

	    else: # checks files which their size < 50 mb
               resultlist = []
               for i in self.tabconlayout.mainlist.getListItems():
                   FileObject = CUnit(i)
                   FileObject.CheckSum(ctype)
                   result = FileObject.ValueReal + "  " + FileObject.Name
                   print makeGreen( "<- " + result)
                   resultlist.append(result)
               self.tabconlayout.mainlist.clear()
               for i in resultlist:
                  self.tabconlayout.mainlist.addItem(i)
               self.checkstatus = True
               self.tabconlayout.mainlist.cstatus=False
    def addFiles(self):
        if self.checkstatus is False:
            selecteds = QFileDialog.getOpenFileNames(self, _("Kontrolcu - Add File(s)"),".")
            for i in selecteds:
                print makeBlue("-> " + i)
                self.tabconlayout.mainlist.addItem(i)

# Error Messages
    def showError(self, errorText):
        QMessageBox.critical(self, "Kontrolcu" + " - " + _("Error"), errorText)
    def showWarning(self, warningText):
        QMessageBox.warning(self, "Kontrolcu" + " - " + _("Warning"), warningText)
    def showInformation(self, informText):
        QMessageBox.information(self, "Kontrolcu" + " - " + _("Information"), informText)
    
        
#This is not important, let it stay here...

if platform.system() != 'Linux':
    app = QApplication(sys.argv)
    form = MainQt()
    form.show()
    app.exec_()

